<?php

namespace MyApp\Controller;

use RedBean_Facade as R;

class AdminController extends \SlimController\SlimController
{   
    public function gameoverAction()
    {
        $this->render('home/gameover');
    }
    
    public function countAction()
    {
        if ($this->app->request->get('secret') != '95589'){
            die('illegal access');
        }
        
        $total = R::count('user');
        $this->render('home/count', array(
            'total' => $total,
            'nb1' => R::count('raffleresult', ' reward = 1 '),
            'nb2' => R::count('raffleresult', ' reward = 2 '),
            'nb3' => R::count('raffleresult', ' reward = 3 ')
        ));
    }
    
    public function exportAction()
    {
        $result = R::getAll('SELECT u.nick, u.name, u.mobile, r.reward FROM raffleresult r LEFT JOIN user u ON r.uid = u.id ORDER BY r.reward ASC');
        $data = [];
        $data[] = ['昵称', '姓名', '电话', '奖品'];
        foreach ($result as $r) {
            $row = ['nick' => $r['nick'],'name' => $r['name'], 'mobile' => $r['mobile'], 'reward' => $r['reward']];
            $data[] = $row; 
        }

        $objPHPExcel = new \PHPExcel();
        $objPHPExcel->getProperties()->setCreator("Kail")
                    ->setTitle('太平95589用户数据')
                    ->setSubject('太平95589用户数据');
        $objPHPExcel->setActiveSheetIndex(0);
        $sheet = $objPHPExcel->getActiveSheet();
        $sheet->setTitle('数据')->fromArray($data, null, 'A1');
        
        $index = 1;
        foreach ($data as $d) {
            if (isset($d['mobile'])) {
                $sheet->setCellValueExplicit(
                    'C' . $index, $d['mobile'], \PHPExcel_Cell_DataType::TYPE_STRING
                );
            }
            ++$index;
        }
        
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $fileName = '95589.xlsx';
        $objWriter->save("app/cache/$fileName");

        header("Content-disposition: attachment; filename=$fileName");
        header("Content-type: text/vnd.ms-excel;charset=utf-8");
        readfile("app/cache/$fileName");
    }
}